package cn.mrlong.base.ktnet.adapter

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okio.Buffer
import retrofit2.Converter
import java.io.OutputStreamWriter
import java.nio.charset.Charset

/**
 * 作者：BINGO
 * 时间：2021/04/25 17:35
 */
class MGsonRequestBodyConverter<T> internal constructor(
    private val gson: Gson,
    private val adapter: TypeAdapter<T>
) : Converter<T, RequestBody> {

    override fun convert(value: T): RequestBody? {
        val buffer = Buffer()
        val writer = OutputStreamWriter(buffer.outputStream(), UTF_8)
        val newJsonWriter = gson.newJsonWriter(writer)
        adapter.write(newJsonWriter,value)
        newJsonWriter.close()
        return RequestBody.create(MEDIA_TYPE,buffer.readByteString())
    }
    companion object{
        val MEDIA_TYPE = ("application/json;charset=UTF-8").toMediaType()
        val UTF_8  = Charset.forName("UTF-8");
    }
}